import type { FC } from 'react'
import React, { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import RemoveEffectVarConfirm from '../../_base/components/remove-effect-var-confirm'
import useConfig from './use-config'
import type { SpeechGeneratorNodeType } from './types'
import VarList from '@/components/workflow/nodes/_base/components/variable/var-list'
import OutputVarList from '@/components/workflow/nodes/_base/components/variable/output-var-list'
import AddButton from '@/components/base/button/add-button'
import Field from '@/components/workflow/nodes/_base/components/field'
import Split from '@/components/workflow/nodes/_base/components/split'
import TypeSelector from '@/components/workflow/nodes/_base/components/selector'
import { InputVar, SupportUploadFileTypes, UploadFileSetting, ValueSelector, Var, VarType, type NodePanelProps } from '@/components/workflow/types'
import BeforeRunForm from '@/components/workflow/nodes/_base/components/before-run-form'
import InputSupportSelectVar from '@/components/workflow/nodes/_base/components/input-support-select-var'
import VarReferencePicker from '@/components/workflow/nodes/_base/components/variable/var-reference-picker'
import ModelParameterModal from '@/components/header/account-setting/model-provider-page/model-parameter-modal'
import ResultPanel from '@/components/workflow/run/result-panel'
import cn from '@/utils/classnames'
import FileUploadSetting from '@/components/workflow/nodes/_base/components/file-upload-setting'
import ActionButton from '@/components/base/action-button'
import {
  RiAttachmentLine,
  RiUploadCloud2Line,
} from '@remixicon/react'
import {
  FileContextProvider,
  useFileStore,
} from '@/components/base/file-uploader/store'

import { Switch, Radio, Tabs, Select, Space, Button, Input } from 'antd'
import type { RadioChangeEvent } from 'antd';
import type { CheckboxGroupProps } from 'antd/es/checkbox';
import type { TabsProps } from 'antd';
import useAvailableVarList from '../../_base/hooks/use-available-var-list'
import { FILE_EXTS } from '@/components/base/prompt-editor/constants'
import FileInput from '@/components/base/file-uploader/file-input'
import { TransferMethod } from '@/services/types/app'
import { ModelTypeEnum } from '@/components/header/account-setting/model-provider-page/declarations'

const i18nPrefix = 'workflow.nodes.speechGenerator'

const Panel: FC<NodePanelProps<SpeechGeneratorNodeType>> = ({
  id,
  data,
}) => {
  const { t } = useTranslation()

  const [isFocus, setIsFocus] = useState(false)

  const { availableVars, availableNodesWithParent } = useAvailableVarList(id, {
    onlyLeafNodeVar: false,
    filterVar: (varPayload: Var) => {
      return [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
    },
  })

  const {
    readOnly,
    inputs,
    outputKeyOrders,
    handleVarListChange,
    handleAddVariable,
    handleRemoveVariable,
    handleCompletionParamsChange,
    handleTextChange,
    handlePromptSpeechChange,
    handlePromptSpeechTemplateChange,
    handlePromptSpeechSelectorChange,
    handlePromptSpeechType,
    handlePromptSpeechTemplate,
    handleVarsChange,
    handleModelChanged,
    handleAddOutputVariable,
    filterVar,
    isShowRemoveVarConfirm,
    hideRemoveVarConfirm,
    onRemoveVarConfirm,
    // single run
    isShowSingleRun,
    hideSingleRun,
    runningStatus,
    handleRun,
    handleStop,
    runResult,
  } = useConfig(id, data)

  const renderTrigger = useCallback((open: boolean) => {
    return (
      <ActionButton
        size='l'
        className={cn(open && 'bg-state-base-hover')}
      >
        <RiAttachmentLine className='w-5 h-5' />
      </ActionButton>
    )
  }, [])
  const model = inputs.model

  return (
    <FileContextProvider>
      <div className='px-4 pt-4 pb-2'>
        <Field title={t(`${i18nPrefix}.model`)}>
          <ModelParameterModal
            popupClassName='!w-[387px]'
            isInWorkflow
            modelType={ModelTypeEnum.tts}
            isAdvancedMode={true}
            mode={model?.mode}
            provider={model?.provider}
            completionParams={model?.completion_params}
            modelId={model?.name}
            setModel={handleModelChanged}
            onCompletionParamsChange={handleCompletionParamsChange}
            hideDebugWithMultipleModel
            debugWithMultipleModel={false}
            readonly={readOnly}
          />
        </Field>
        <Field title={t(`需要生成语音的文本`)} >
          <InputSupportSelectVar
            instanceId='http-api-url'
            className={'shadow-xs bg-gray-50 border-gray-300 rounded-lg px-3 py-[6px] border'}
            value={inputs.text}
            promptMinHeightClassName={'min-h-[100px]'}
            onChange={handleTextChange}
            readOnly={readOnly}
            nodesOutputVars={availableVars}
            availableNodes={availableNodesWithParent}
            placeholder={!readOnly ? t('workflow.nodes.http.apiPlaceholder')! : ''}
            placeholderClassName='!leading-[21px]'
          ></InputSupportSelectVar>
        </Field>
      </div>
      <div className='px-4 pb-4 space-y-4'>
        <Tabs defaultActiveKey={'template'} activeKey={inputs.prompt_speech_type} items={[
          {
            key: 'clone_with_var',
            label: '克隆声音(变量)',
            children: <div className='px-4 pt-4 pb-2'>
              <Field title={t(`声音样本`)}>
                <VarReferencePicker
                  readonly={readOnly}
                  nodeId={id}
                  isShowNodeName
                  value={inputs.prompt_speech_selector?.prompt_speech_selector}
                  onChange={(value, varKindType, varInfo) => {
                    handlePromptSpeechSelectorChange(value as ValueSelector, inputs.prompt_speech_selector?.prompt_text_selector);
                  }}
                  filterVar={(payload, valueSelector: ValueSelector) => { return true }}
                  valueTypePlaceHolder={''}
                  placeholder={t('workflow.nodes.assigner.setParameter') as string}
                  minWidth={352}
                  popupFor='toAssigned'
                  className='w-full'
                />
              </Field>
              <Field title={t(`样本文本`)} >
                <VarReferencePicker
                  readonly={readOnly}
                  nodeId={id}
                  isShowNodeName
                  value={inputs.prompt_speech_selector?.prompt_text_selector}
                  onChange={(value, varKindType, varInfo) => {
                    handlePromptSpeechSelectorChange(inputs.prompt_speech_selector?.prompt_speech_selector, value as ValueSelector);
                  }}
                  filterVar={(payload, valueSelector) => { return true }}
                  valueTypePlaceHolder={''}
                  placeholder={t('workflow.nodes.assigner.setParameter') as string}
                  minWidth={352}
                  popupFor='toAssigned'
                  className='w-full'
                />
              </Field>
            </div>,
          },
          {
            key: 'clone',
            label: '克隆声音',
            children: <div className='px-4 pt-4 pb-2'>
              <Field title={t(`声音样本`)}>
                <Button className='relative w-full' >
                  <RiUploadCloud2Line className='mr-1 w-4 h-4' />
                  {t('common.fileUploader.uploadFromComputer')}
                  <FileInput
                    fileConfig={{
                      image: {
                        enabled: false
                      },
                      allowed_file_types: [],
                      allowed_file_extensions: [],
                      number_limits: 1,
                    }}
                  />
                </Button>
              </Field>
              <Field title={t(`样本文本`)} >
                <InputSupportSelectVar
                  instanceId='prompt_speech_text'
                  className={'shadow-xs bg-gray-50 border-gray-300 rounded-lg px-3 py-[6px] border'}
                  value={inputs.prompt_speech?.prompt_text}
                  promptMinHeightClassName={'min-h-[40px]'}
                  onChange={(text) => {
                    handlePromptSpeechChange(text, inputs.prompt_speech?.prompt_speech);
                  }}
                  readOnly={readOnly}
                  nodesOutputVars={availableVars}
                  availableNodes={availableNodesWithParent}
                  placeholder={!readOnly ? t(`${i18nPrefix}.speechTextPlaceholder`)! : ''}
                  placeholderClassName='!leading-[21px]'
                ></InputSupportSelectVar>
              </Field>
            </div>,
          },
          {
            key: 'template',
            label: '内置声音',
            children: <div className='px-4 pt-4 pb-2'>
              <Field title={t(`性别`)} >
                <Select
                  defaultValue="女"
                  style={{ width: '100%' }}
                  options={[{ value: '女', label: '女' }, { value: '男', label: '男' }]}
                />
              </Field>
              <Field title={t(`模板`)} >
                <Select
                  defaultValue="lucy"
                  style={{ width: '100%' }}
                  options={[{ value: 'lucy', label: 'Lucy' }]}
                />
              </Field>
            </div>,
          },
        ]} onChange={handlePromptSpeechType} />
        <Split />
        {
          isShowSingleRun && (
            <BeforeRunForm
              nodeName={inputs.title}
              onHide={hideSingleRun}
              forms={[
              ]}
              runningStatus={runningStatus}
              onRun={handleRun}
              onStop={handleStop}
              result={<ResultPanel {...runResult} showSteps={false} />}
            />
          )
        }
        <RemoveEffectVarConfirm
          isShow={isShowRemoveVarConfirm}
          onCancel={hideRemoveVarConfirm}
          onConfirm={onRemoveVarConfirm}
        />
      </div >
    </FileContextProvider>
  )
}

export default React.memo(Panel)
